<?php

/**
 * WP Showroom Admin Ajax Requests
 *
 * @package
 */

ini_set('memory_limit', '64M');

require_once '../../../wp-config.php';
require_once '../../../wp-admin/admin.php';
require_once 'wpsr.php';
require_once 'wpsr.admin.php';
require_once 'wpsr.file.php';
require_once 'wpsr.thumb.php';


global $user_ID;


$wpsr = new WPsrAdm;
$wpsr->WPsrUser();

$event = $_GET['event'];
$id = (int) $_GET['id'];


/**
 * Edit Album
 */
if ($event == 'editalb') {
	$wpsr->obj = $wpsr->getAlbById($id);
	$wpsr->path = $wpsr->getPath($wpsr->obj->id);
	$wpsr->AdmSecurityManager();
	//$album = $wpsr->getAlbums(1, 0, NULL, $wpsr->obj->id);
	$album = $wpsr->getAlbList();	
	
	//$hasChild = $wpsr->checkForChild($wpsr->obj->id);

	if ( count($wpsr->error) < 1 ) {
?>
	<form name="editalbum" method="post" action="../wp-content/plugins/WPshowroom/post.php" />
	<input name="event" type="hidden" value="editAlbum">
	<input name="aid" type="hidden" value="<?php echo $id; ?>">
	<input name="faid" type="hidden" value="<?php echo $wpsr->obj->paid; ?>" />
	<table border="0" cellspacing="5" cellpadding="0" width="100%" class="WPSR_tbledit">
		<tr>
			<td>
				<label for="title-<?php echo $id; ?>">Album Title:</label>
			</td>
			<td>
				<input class="WPSR_tblinput" id="title-<?php echo $id; ?>" type="text" value="<?php echo $wpsr->obj->title; ?>" name="title-<?php echo $id; ?>"/>
			</td>
			<td>
				<label for="comments-<?php echo $id; ?>">Comments:</legend>
			</td>
			<td>
				<label for="comments-<?php echo $id; ?>" style="font-size:11px;">
					<input id="comments-<?php echo $id; ?>" type="checkbox" value="1" 
<?php
					if ($wpsr->obj->com == 1) {
						echo 'checked="checked" ';
					}
?> 
					name="comments-<?php echo $id; ?>"/>
					Allow comments on pictures in this Album
				</label>
			</td>
		</tr>
		<tr>
			<td>
				<label for="desc-<?php echo $id; ?>">Description:</label>
			</td>
			<td>
				<input class="WPSR_tblinput" id="desc-<?php echo $id; ?>" type="text" size="40" value="<?php echo $wpsr->obj->description; ?>" name="desc-<?php echo $id; ?>"/>
			</td>
			<td>
				<label for="level-<?php echo $id; ?>">Level:</label>
			</td>
			<td>
				<select id="level-<?php echo $id; ?>" name="level-<?php echo $id; ?>">
<?php
					for ($i=0; $i < 11; $i++) {
						echo "<option value='$i'";
						if ($wpsr->obj->level == $i) {
							echo " selected='selected'";
						}
						echo ">Userlevel $i</option>\n";
					}
?>
				</select>
			</td>
		</tr>
		<tr>
			<td>
				<label for="meta-<?php echo $id; ?>">Meta Information:</label>
			</td>
			<td>
				<input class="WPSR_tblinput" id="meta-<?php echo $id; ?>" type="text" value="<?php echo $wpsr->obj->meta; ?>" name="meta-<?php echo $id; ?>"/>
			</td>
			<td colspan="2">
				&nbsp;
			</td>						
		</tr>
		<tr>
			<td>
				<label for="parent-<?php echo $id; ?>">Parent Album:</label>
			</td>
			<td>
				<select id="parent-<?php echo $id; ?>" name="parent-<?php echo $id; ?>">
					<option value="1"><?php echo WPSR_BASE_NAME; ?></option>
<?php
					foreach ($album as $aid => $title) {
						echo "<option value='$aid'";
						if ($aid == $wpsr->obj->paid) {
							echo " selected='selected'";
						}
						echo ">".$title."</option>\n";
					}
?>
				</select>
			</td>
			<td>

			</td>
			<td>

			</td>
		</tr>
		<tr>
			<td colspan="2" align="left">
				<input class="button" type="submit" name="delete" value="Delete Album" onclick="if ( confirm('You are about to delete this Album \'<?php echo $wpsr->obj->title; ?>\' with all Pictures!\n \'Cancel\' to stop, \'OK\' to delete.') ) { return true;}return false;" />
			</td>
			<td colspan="2" align="right">
				<input class="button-secondary" type="button" name="cancel" value="Cancel" onclick="WPSR_edit_alb(<?php echo $id; ?>,'WPSR_ed_alb_btn-<?php echo $id; ?>');blur();"/>
				<input class="button-primary" type="submit" name="edit" value=" Save Album "/>
			</td>
		</tr>
	</table>
	</form>
<?php
	}
	else {
		$wpsr->getAdminMessage();
	}
}


/**
 * Edit Picture
 */
elseif ($event == 'editpic') {
	$wpsr->obj = $wpsr->getPicById($id);
	$wpsr->path = $wpsr->getPath($wpsr->obj->id);
	$wpsr->AdmSecurityManager();
	$album = $wpsr->getAlbList();
	if ( count($wpsr->error) < 1 ) {
?>
	<form name="editpicture" method="post" action="../wp-content/plugins/WPshowroom/post.php" />
	<input name="event" type="hidden" value="editPicture">
	<input name="pid" type="hidden" value="<?php echo $id; ?>">
	<input name="aid" type="hidden" value="<?php echo $wpsr->obj->aid; ?>">
	<table border="0" cellspacing="5" cellpadding="0" width="100%" class="WPSR_tbledit">
		<tr>
			<td>
				<label for="cover-<?php echo $id; ?>">Make Picture the Album-Cover of:</label>
			</td>
			<td>
				<label for="caption-<?php echo $id; ?>">Caption:</label>
			</td>
			<td>
				<input class="WPSR_tblinput" type="text" name="caption-<?php echo $id; ?>" value="<?php echo $wpsr->obj->caption; ?>" id="caption-<?php echo $id; ?>">
			</td>
			<td>
				<label for="hits-<?php echo $id; ?>">Hits:</label>
			</td>
			<td>
				<input class="WPSR_tblinput" type="text" name="hits-<?php echo $id; ?>" value="<?php echo $wpsr->obj->hits; ?>" id="hits-<?php echo $id; ?>">
			</td>
		</tr>
		<tr>
			<td>
				<select id="cover-<?php echo $id; ?>" name="cover-<?php echo $id; ?>">
					<option value="1"><?php echo WPSR_BASE_NAME; ?></option>
<?php
					foreach ($album as $aid => $title) {
						echo "<option value='$aid'";
						if ($aid == $wpsr->obj->aid) {
							echo " selected='selected'";
						}
						echo ">".$title."</option>\n";
					}
?>
				</select>				
			</td>
			<td>
				<label for="parent-<?php echo $id; ?>">Move Picture to:</label>
			</td>
			<td>
				<select id="parent-<?php echo $id; ?>" name="parent-<?php echo $id; ?>">
					<option value="1"><?php echo WPSR_BASE_NAME; ?></option>
<?php
					foreach ($album as $aid => $title) {
						echo "<option value='$aid'";
						if ($aid == $wpsr->obj->aid) {
							echo " selected='selected'";
						}
						echo ">".$title."</option>\n";
					}
?>
				</select>
			</td>
			<td>
				<label for="level-<?php echo $id; ?>">Level:</label>
			</td>
			<td>
				<select id="level-<?php echo $id; ?>" name="level-<?php echo $id; ?>">
<?php
				for ($i=0; $i < 11; $i++) {
					echo "<option value='$i'";
					if ($wpsr->obj->level == $i) {
						echo " selected='selected'";
					}
					echo ">Userlevel $i</option>\n";
				}
?>
				</select>
			</td>
		</tr>
		<tr>
		<tr>
			<td>
				<input class="button" type="submit" name="cover" value="Album Cover" onclick="if ( confirm('You are about to make this picture \'<?php echo $wpsr->obj->file; ?>\' an Album-Cover. Right now you can only overwrite, not delete Album Covers... Sucks, ne? \n \'Cancel\' to stop, \'OK\' to procede.') ) { return true;}return false;" /> 
			</td>
			<td colspan="2" align="left">
				<input class="button" type="submit" name="delete" value="Delete Picture" onclick="if ( confirm('You are about to delete this picture \'<?php echo $wpsr->obj->file; ?>\'\n \'Cancel\' to stop, \'OK\' to delete.') ) { return true;}return false;" /> 
			</td>
			<td colspan="2" align="right">
				<input class="button-secondary" type="button" name="cancel" value="Cancel" onclick="WPSR_edit_pic(<?php echo $id; ?>,'WPSR_ed_pic_btn-<?php echo $id; ?>');blur();"/>
				<input class="button-primary" type="submit" name="edit" value=" Save Picture "/>
			</td>
		</tr>
	</table>
	</form>
<?php
	}
	else {
		$wpsr->getAdminMessage();
	}
}


/**
 * Load DIVs
 */
elseif ($event == 'loaddiv') {
	
	/**
	 * Load Upload Picture DIV
	 */
	if ($id == 1) {
?>
		<div class="tablenav">
			<div class="alignright">
				<input class="button-primary" type="button" name="addpic" value="+ Add Pictures to Album" onclick="WPSR_goto('<?php bloginfo('wpurl'); ?>/wp-admin/admin.php?page=WPsr-pictures')"/>
			</div>
		</div>

		<br class="clear"/>
<?php
	}
	
	/**
	 * Load Assign to Album List DIV
	 */
	elseif ($id == 2) {
		if ( count($wpsr->error) < 1 ) {
			$wpsr->albums = $wpsr->getAlbums(1, 0, $depth);
			$allalb = $wpsr->albums;
		}
?>
		to: <select id="parent-0" name="palb">
			<option value="1"><?php echo WPSR_BASE_NAME; ?></option>
<?php
			foreach ($allalb as $alb) {
				echo "<option value='$alb->aid'>".str_repeat('—', $alb->intend).' '.$alb->title."</option>\n";
			}
?>
		</select>
		<input type="hidden" name="event" value="assign" id="event">
		<select name="level">
<?php
			for ($i=0; $i < 11; $i++) {
				echo "<option value='$i'>Userlevel $i</option>\n";
			}
?>
		</select> <input id="doaction" class="button-secondary action" type="submit" name="doaction" value="Apply"/>
<?php
	}
	
	/**
	 * Load Delete Picture Queue Warning DIV
	 */
	elseif ($id == 3) {
?>
		<input type="hidden" name="event" value="deleteuploads" id="event">
		<span style="color:#FF0000;font-weight:bold;"> Warning: Pictures will be deleted! </span><input id="doaction" class="button-secondary action WPSR_delete" type="submit" name="doaction" value="Apply"/>
<?php
	}
	
	/**
	 * Load Unassign Button DIV
	 */
	elseif ($id == 4) {
?>
		<input type="hidden" name="event" value="unassign" id="event">
		<input id="doaction" class="button-secondary action" type="submit" name="doaction" value="Apply"/>
<?php
	}
	
	/**
	 * Load Mass Edit Picture Div
	 */
	elseif ($id == 5) {
		$album = $wpsr->getAlbList();
		$aid = (int) $_GET['aid'];
?>
		<table border="0" cellspacing="5" cellpadding="0" width="100%" class="WPSR_tbledit">
			<tr>
				<td>
					<input id="docaption" type="checkbox" value="1" name="docaption"/>
					<label for="caption">Caption:</label>
				</td>
				<td>
					<input class="WPSR_tblinput" type="text" name="caption" value="" id="caption" onChange="WPSR_check('docaption');">
				</td>
				<td>
					<input id="dohits" type="checkbox" value="1" name="dohits"/>
					<label for="hits">Hits:</label>
				</td>
				<td>
					<input class="WPSR_tblinput" type="text" name="hits" value="" id="hits" onChange="WPSR_check('dohits');">
				</td>
			</tr>
			<tr>
				<td>
					<input id="doparent" type="checkbox" value="1" name="doparent"/>
					<label for="parent">Move Picture to:</label>
				</td>
				<td>
					<select id="parent" name="parent" onChange="WPSR_check('doparent');">
						<option value="1"><?php echo WPSR_BASE_NAME; ?></option>
<?php
					foreach ($album as $key => $title) {
						echo "<option value='$key'";
						if ($key == $aid) {
							echo " selected='selected'";
						}
						echo ">".$title."</option>\n";
					}
?>
					</select>
				</td>
				<td>
					<input id="dolevel" type="checkbox" value="1" name="dolevel"/>
					<label for="level">Level:</label>
				</td>
				<td>
					<select id="level" name="level" onChange="WPSR_check('dolevel');">
<?php
					for ($i=0; $i < 11; $i++) {
						echo "<option value='$i'";
						echo ">Userlevel $i</option>\n";
					}
?>
					</select>
				</td>
			</tr>
			<tr>
				<td colspan="2" align="left">
					<input class="button" type="submit" name="delete" value="Delete Pictures" onclick="if ( confirm('You are about to delete these pictures. \n \'Cancel\' to stop, \'OK\' to delete.') ) { return true;}return false;" />
					<!-- <input class="button" type="submit" name="regenerate" value="Regenerate Thumbnails" onclick="if ( confirm('You are about to delete these pictures. \n \'Cancel\' to stop, \'OK\' to delete.') ) { return true;}return false;" /> -->
				</td>
				<td colspan="2" align="right">
					<input class="button-secondary" type="button" name="cancel" value="Cancel" onclick="WPSR_peoptions(<?php echo $aid; ?>,'WPSR-mepb');blur();"/>
					<input class="button-primary" type="submit" name="edit" value=" Save Pictures "/>
				</td>
			</tr>
		</table>
<?php
	}
	
	/**
	 * Load Mass Delete Picture Button
	 */
	elseif ($id == 6) {
?>
		<input type="hidden" name="event" value="unassign" id="event">
		<input id="doaction" class="button-secondary action WPSR_delete" type="submit" name="doaction" value="Apply"/>
		<?php
	}
}


/**
 * Load Thumbnail Preview
 */
elseif ($event == 'loadthumb') {
?>
	<div style="width:200px;height:200px;background:url('../wp-content/plugins/WPshowroom/showimg.php?file=<?php echo $_GET['file']; ?>&where=<?php echo $_GET['where']; ?>') center center no-repeat;">&nbsp;</div>
<?php
}


/**
 * Insert Picture & generate thumbnails
 */
elseif ($event == 'insert') {
	global $user_ID, $wpdb;

	ob_start();

	$wfile = WPsrFile::getWaitingFile($user_ID, 1);

	if ($wfile->id) {
		$path = $_GET['path'];
		$filename = WPsrFile::IfExistsRename($wfile->file, WPSR_ORG_FILEPATH.$path);
		$psizes = explode(",", WPSR_PSIZES);
		for ($i = 0; $i < count($psizes); $i++) {
			if ($psizes[$i] != 'full') {
				/**
				 * Thumbnails
				 */
				$file = WPSR_FILEPATH."waiting/".$user_ID."/".$wfile->file;
				$output = WPSR_FILEPATH.$psizes[$i].'/'.$path;
				$size = explode("_", $psizes[$i]);
				$psize = explode("x", $size[0]);
				if ($size[1] == 'nc' || $size[1] == 'ncw') {
					$doCrop = false;
				}
				else {
					$doCrop = true;
				}
				if ( $wfile->xsize > $wfile->ysize ) {
					// querformat
					$crop = ($wfile->ysize)/2;
					$picsize = $psize[0];
				}
				else {
					//hochformat
					$crop = ($wfile->xsize)/2;
					$picsize = $psize[1];
				}
				$croparray = array(2, 1, $crop, $crop, $crop, $crop);
				if ($size[1] == 'cw' || $size[1] == 'ncw') {
					$doWM = true;
				}
				else {
					$doWM = false;
				}
				$thumb = WPsrThumb::makethumbnail($file, $output, $picsize, 80, $doCrop, $croparray, $filename, $doWM );
			}
		}
		
		/**
		 * Move Original File
		 */
		rename($file, WPSR_ORG_FILEPATH.$path.$filename);

		/**
		 * DB Entries
		 */
		$dbok = true;
		
		/**
		 * Referenz
		 */
		$date = date('Y-m-d H:m:s');
		$id = NULL;
		$type = 2;
		$owner = $user_ID;
		$level = $wfile->level;
		if (!$wpdb->insert(WPSR_DB_R, compact('id', 'type', 'date', 'owner', 'level'))) $dbok = false;

		/**
		 * Picture
		 */
		$pid = (int) $wpdb->insert_id;
		$aid = $wfile->album;
		$file = $filename;
		$caption = NULL;
		$width = $wfile->xsize;
		$height = $wfile->ysize;
		$hits = 0;
		if (!$wpdb->insert(WPSR_DB_P, compact('pid', 'aid', 'path', 'file', 'caption', 'width', 'height', 'hits'))) $dbok = false;

		/**
		 * History
		 */
		$done_date = $date;
		$type = 5;
		if (!$wpdb->update(WPSR_DB_I, compact('done_date', 'type'), array('id' => $wfile->id))) $dbok = false;

		/**
		 * TODO: Error Reporting für alle thumbnails etc. angeben
		 */
?>
		<span style="font-size:12px;">Processing file <strong><?php echo $filename; ?></strong></span><br />
		<span style="line-height:35px;">Album <?php echo $wfile->album; ?> | Level <?php echo $wfile->level; ?> | <?php echo $wfile->xsize; ?>x<?php echo $wfile->ysize; ?>px | <?php echo $wfile->fsize; ?></span><br />
		<span style="display:inline-block;width:300px;">Database entry:</span><?php if ($dbok) echo "ok"; else echo "FAILED"; ?><br />

		<script type="text/javascript" charset="utf-8">
			insertcount = insertcount+1;
			inserttogo = inserttogo-1;
			insertpercent = Math.ceil((insertcount/inserttotal)*200);
			insertpercentval = Math.ceil((insertcount/inserttotal)*100);
			$('insertbar').setStyle('width',insertpercent);
			$('insertpercent').set('text', insertpercentval);
			$('wpsrfd').set('text', insertcount);
			$('wpsrfg').set('text', inserttogo);
			WPSR_insertpics('<?php echo $path; ?>');
		</script>
<?php
	}
	else {
?>
		All files done!
<?php
	}
	ob_end_flush();
}

/**
 * Insert Picture & generate thumbnails
 */
elseif ($event == 'regenerate') {
	global $user_ID, $wpdb;

	ob_start();

	$wfile = WPsrFile::getWaitingFile($user_ID, 2);

	if ($wfile->id) {
		$path = $wfile->path;
		$psizes = explode(",", WPSR_PSIZES);
		$filename = $wfile->file;
		if (WPsrFile::checkPicDirs($path) == true) {
			$file = WPSR_ORG_FILEPATH.$wfile->path.$wfile->file;
			$imagesize = getimagesize($file);
			for ($i = 0; $i < count($psizes); $i++) {
				if ($psizes[$i] != 'full') {
					/**
					 * Thumbnails
					 */
					$output = WPSR_FILEPATH.$psizes[$i].'/'.$path;
					$size = explode("_", $psizes[$i]);
					$psize = explode("x", $size[0]);
					if ($size[1] == 'nc' || $size[1] == 'ncw') {
						$doCrop = false;
					}
					else {
						$doCrop = true;
					}
					if ( $imagesize[0] > $imagesize[1] ) {
						// querformat
						$crop = $imagesize[1]/2;
						$picsize = $psize[0];
					}
					else {
						//hochformat
						$crop = $imagesize[0]/2;
						$picsize = $psize[1];
					}
					$croparray = array(2, 1, $crop, $crop, $crop, $crop);
					if ($size[1] == 'cw' || $size[1] == 'ncw') {
						$doWM = true;
					}
					else {
						$doWM = false;
					}
					if (file_exists($output.$filename)) {
						unlink($output.$filename);
					}
					$thumb = WPsrThumb::makethumbnail($file, $output, $picsize, 80, $doCrop, $croparray, $filename, $doWM );
				}
			}
		}
		
		/**
		 * History
		 */
		$done_date = date('Y-m-d H:m:s');
		$type = 6;
		if (!$wpdb->update(WPSR_DB_I, compact('done_date', 'type'), array('id' => $wfile->id))) $dbok = false;

		/**
		 * TODO: Error Reporting für alle thumbnails etc. angeben
		 */
?>
		<span style="font-size:12px;">Thumbnails regenerated for <strong><?php echo $filename; ?></strong></span><br />
		<script type="text/javascript" charset="utf-8">
			insertcount = insertcount+1;
			inserttogo = inserttogo-1;
			insertpercent = Math.ceil((insertcount/inserttotal)*200);
			insertpercentval = Math.ceil((insertcount/inserttotal)*100);
			$('insertbar').setStyle('width',insertpercent);
			$('insertpercent').set('text', insertpercentval);
			$('wpsrfd').set('text', insertcount);
			$('wpsrfg').set('text', inserttogo);
			WPSR_regenratepics();
		</script>
<?php
	}
	else {
?>
		All files done!
<?php
	}
	ob_end_flush();
}


/**
 * Debug: Form
 */
elseif ($event == 'form') {
	// print "<pre>".print_r($_POST, true)."</pre>";
	wp_redirect('http://www.google.com', 302);
}

?>
